import axios from "axios";
import router from "../router/index";

const request = axios.create({
  method: "get",
  baseURL: "http://geek.itheima.net/v1_0",
  timeout: 5000,
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response.status === 401) {
      localStorage.removeItem("token");
      router.navigate("/login");
      // 跳转登录页失败, 强制刷新一下
      window.location.reload();
    }
    return Promise.reject(error);
  }
);

export { request };
